﻿CREATE PROCEDURE [dbo].[AbsenceDocInsert]
(--Отказ покупателю в случае отсутствия товара в продаже
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @DepartmentUserId int
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

--IF (@ContragentId Is Null)
--BEGIN
--	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
--	RAISERROR (@strMsg, 11, @intErrCode)
--	RETURN @intErrCode
--END

IF @DocNumber Is Null
BEGIN
	exec [dbo].[GetNextDocNumber] 14, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 
--ELSE SET @DocDate = dbo.NormalizeDate(@DocDate)

SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], 
DepartmentUserId, [Note], [MD], [MW]) 
VALUES (@intNextId, 14, @DocDate, @DocNumber, 
@DepartmentUserId, @Note, @MD, @MW);
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
DepartmentUserId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)
RETURN 0

